package com.yass.zaika.process;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.yass.zaika.Zaika;
 

public class Process {

	public boolean processInputs(ArrayList<String> ingredients, int meal_time,
			String meal_type, Zaika application) {
		
		// serialize input and send to server
		String result = null;
    	try{
    		HttpParams httpParameters = new BasicHttpParams();
    		HttpConnectionParams.setConnectionTimeout(httpParameters, 6000);
    		HttpConnectionParams.setSoTimeout(httpParameters, 30000);

		    HttpClient client = new DefaultHttpClient(httpParameters);
		    // set the GET URL
		    String req = "http://zaika.boldwebservices.com/recipes/find_recipes/";
		    // append the ingredients
		    for(int i = 0; i < ingredients.size(); i++) {
		    	req += ingredients.get(i);
		    	if(i != ingredients.size() - 1) {
		    		req += ",";
		    	}
		    }
		    // append type
		    req += "/" + meal_type;
		    // append time
		    req += "/" + meal_time;
		    
			HttpGet get = new HttpGet(req);
			// get the response
			HttpResponse responseGet = client.execute(get);
			HttpEntity resEntityGet = responseGet.getEntity();
			if (resEntityGet != null) {  
				// convert the response to a String
				result = EntityUtils.toString(resEntityGet);
		    }
		} catch (IOException e) {
			System.out.println("Encountered exception: " + e.getMessage());
		}
		
		
		if(result == null)
			return false;
		
		try {
			JSONArray recipes = (JSONArray) new JSONTokener(result).nextValue();
			for(int i = 0; i < recipes.length(); i++) {
				JSONObject recipe = recipes.getJSONObject(i).getJSONObject("Recipe");
				String meal_name = recipe.getString("meal_name");
				String meal_description = recipe.getString("meal_description");
				int time = recipe.getInt("meal_time");
				application.getDisplay().addResult(time, meal_description, meal_name);
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
}
